package com.ok.common.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.ok.common.ext.toast
import java.lang.reflect.ParameterizedType

abstract class BaseVMActivity<VM : BaseViewModel, VB : ViewBinding> : BaseActivity<VB>() {

    lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        createViewModel()
        registerEvent()
        super.onCreate(savedInstanceState)
    }

    private fun registerEvent() {
        mViewModel.ui.showDialog.observe(this) {
            showLoading(it)
        }
        mViewModel.ui.dismissDialog.observe(this) {
            dismissLoading()
        }
        mViewModel.ui.toast.observe(this) {
            toast(it)
        }
        mViewModel.ui.msgEvent.observe(this) {
            handleEvent(it)
        }
    }

    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class<VM>
            mViewModel = ViewModelProvider(viewModelStore, ViewModelProvider.NewInstanceFactory())[clazz]
            lifecycle.addObserver(mViewModel)
        }
    }

}